<?php
declare (strict_types = 1);

namespace app\controller\api;

use app\BaseController;
use app\constant\CommonConstant;
use app\constant\ModelConstant;
use app\exception\BusinessException;
use app\exception\PaypalBusinessException;
use app\libs\AsiabillSDK\action\SessionAsiabill;
use app\logic\OrderLogic;
use app\model\IpLogs;
use app\model\Notify;
use app\model\OrderLogs;
use app\model\Orders;
use app\model\Shops;
use app\model\ShopsPayment;
use app\service\payment\gateway\PaymentBase;
use app\service\payment\gateway\PaypalService;
use app\trait\ShopifyTrait;
use app\validate\CardValidate;
use app\validate\OrderValidate;
use app\validate\PlaceOrderValidate;
use app\validate\PrePayValidate;
use think\App;
use think\helper\Arr;
use think\helper\Str;
use think\Request;


class OrderController extends BaseController
{
    use ShopifyTrait;
    protected OrderLogic $logic;
    public function __construct(App $app)
    {
        $this->logic = new OrderLogic();
        parent::__construct($app);
    }

    //创建订单
    public function createDraftOrder(Request $request)
    {

        $data = $this->logic->createDraftOrder($request);
        return $this->success($data);
    }

    //更新订单
    public function modifyDraftOrder(Request $request,Orders $order)
    {
        if($order->order_status == Orders::ORDER_STATUS_COMPLETED) throw new \Exception('order has payed',CommonConstant::ORDER_HAS_PAYED_ERROR_CODE);
        Validate(OrderValidate::class)->check($request->put());
        $data = $this->logic->updateDraftOrder($request, $order);
        return $this->success($data);
   }

    public function getPaymentMethod(Request $request)
    {
        return $this->success(Shops::getEnablePayment($request));
    }

    //下单
    public function placeOrder(Request $request,Orders $order)
    {
        try {
            Notify::saveParams($order->id, ['params' => $request->all()], Notify::TYPE_PLACE_ORDER);
            if ($order->order_status == Orders::ORDER_STATUS_COMPLETED) throw new \Exception('order has payed', CommonConstant::ORDER_HAS_PAYED_ERROR_CODE);
            Validate(PlaceOrderValidate::class)->check($request->post());
            $data = $this->logic->placeOrder($request, $order);
            return $this->success($data);
        }catch (BusinessException $e){
            return json(['code'=>CommonConstant::API_REQUEST_ERROR,'msg'=>$e->getMessage(),'data'=>[]]);
        }catch (\Exception $e){
            return $this->error($e->getMessage(),$e->getCode() ?: 500);
        }

    }

    //获取sessionToken
    public function getSessionToken(Request $request,ShopsPayment $payment)
    {
        try {
            $session = new SessionAsiabill($payment);
            $session_token = $session->get_session_token();
            $js_sdk = $session->getAsiabill()->getJsScript();
            return $this->success(compact('session_token', 'js_sdk'));
        }catch (\Exception $e){
            //dump($e);
            throw new \Exception($e->getMessage());

        }

    }

    //获取所有国家运费
    public function getShippingZones(Request $request)
    {
        $this->validate($request->all(),['country_code'=>'require','sub_total'=>'require']);
        $params = $request->all();
        $params['checkout_id'] = $request->param('checkout_id','');
        $shipping_line = $this->logic->getShippingZones($request);
        return $this->success(compact('shipping_line'));
    }

    //预下单
    public function prePayByPaypal(Request $request)
    {
        $data = $this->logic->quickPay($request);
        return $this->success($data);
    }

    //获取贝宝配置
    public function getPaypalConfig(Request $request)
    {
        $data = $this->logic->getPaypalConfig($request);
        return $this->success($data);
    }

    //获取订单状态
    public function getOrderStatus(Request $request,Orders $order)
    {
        if($order->pay_status == Orders::ORDER_STATUS_FAIL){
            return json(['code'=>'P0088','msg'=>$order->error_msg,'data'=>[]]);
        }else{
            return $this->success(
                [
                    'order_status'=>$order->order_status,
                    'is_support_repurchase'=>$order->is_support_repurchase
                ]);//是否支持重购
        }

    }

    //获取订单详情
    public function getOrderDetail(Request $request,Orders $order)
    {
        $data = $this->logic->getOrderDetail($order);
        return $this->success($data);
    }

    public function getOrderStatusUrl(Request $request,Orders $order)
    {
        if($order->order_status != Orders::ORDER_STATUS_COMPLETED) throw new \Exception("order not completed");
        return $this->success($this->getOrderSuccessUrl($order));
    }

    public function confirmCheckout(Request $request,Orders $order)
    {
        Validate(CardValidate::class)->check($request->post());
        if ($order->order_status == Orders::ORDER_STATUS_COMPLETED) throw new \Exception('order has payed',CommonConstant::ORDER_HAS_PAYED_ERROR_CODE);
        $result = null;
        return $this->success($result);
    }

    public function saveOrderLogs(Request $request)
    {
        $this->validate($request->all(),['checkout_id'=>'require','logs'=>'require']);
        OrderLogs::saveLogs($request);
        return $this->success();
    }

    /**
     * @param Request $request
     * @desc 添加LP日志
     */
    public function saveIPLogs(Request $request)
    {
        $this->validate($request->all(),['lp_type'=>'require']);
        $log = IpLogs::saveIpLogs($request);
        return $this->success(['id'=>$log->id]);
    }



    //获取加购折扣金额
    public function getRepurchaseDiscount()
    {
        $discount = config('payment.discount.value');
        return $this->success(compact('discount'));
    }

    //创建快捷支付草稿订单
    public function createPaypalDraftOrder(Request $request)
    {
        $result = $this->logic->createPaypalDraftOrder($request);
        return $this->success($result);
    }

    //计算total金额
    public function calculateTotalSet(Request $request)
    {
        $subtotal = $request->param('subtotal','0.00');
        $shippingFee = $request->param('shipping_price','0.00');
        $subtotal = (string)$subtotal;
        $shippingFee = (string)$shippingFee;
        $total_price = bcadd($subtotal,$shippingFee,2);
        list($totalPrice,$taxPrice) = Orders::calculateTotalPrice($total_price);
        return $this->success(compact('totalPrice','taxPrice'));
    }

    //计算苹果支付金额
    public function calculateApplePayTotalSet(Request $request){
        $checkout = $request->param('checkout',[]);
        $shipping_line = $request->param('shipping_line',[]);
        $total_price = Arr::get($checkout,'cart.total_price', '0.00');
        $total_price = $total_price > 0 ? bcdiv((string)$total_price,'100',2) : '0.00';
        $shipping_price = Arr::get($shipping_line,'price', '0.00');
        $total_price = bcadd($total_price,$shipping_price,2);
        list($apple_display_amount,$taxPrice) = Orders::calculateTotalPrice($total_price);
        return $this->success(compact('apple_display_amount'));

    }

    /**
     * @param Request $request
     * @param Orders $order
     * @return \think\response\Json
     * @des 谷歌支付和苹果支付 paypal
     */
    public function capturePaypalByGoogleAndApple(Request $request, Orders $order)
    {
        return $this->success($this->logic->capturePaypalByGoogleAndApple($request,$order));
    }

    /**
     * @param Request $request
     * @return \think\response\Json
     * @throws BusinessException
     * @desc spreedly快捷支付 paypal
     */
    public function captureSpreedlyByGoogleAndApple(Request $request)
    {
        return $this->success($this->logic->captureSpreedlyByGoogleAndApple($request));
    }
}
